//
//  HBLaunchGuideView.m
//  HBLibary
//
//  Created by Rambo on 2018/11/3.
//

#import "HBLaunchGuideView.h"

static NSString * const kHBLaunchGuideCellId = @"kHBLaunchGuideCellId";

@interface HBLaunchGuideCell : UICollectionViewCell

@property (nonatomic, strong) UIImageView *imageView;

@end

@implementation HBLaunchGuideCell

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
        UIView *superView = self.contentView;
        
        _imageView = ({
            UIImageView *imageView = [[UIImageView alloc] init];
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.clipsToBounds = YES;
            [superView addSubview:imageView];
            imageView.translatesAutoresizingMaskIntoConstraints = NO;
            NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeLeft multiplier:1 constant:0];
            [superView addConstraint:leftConstraint];
            
            NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeTop multiplier:1 constant:0];
            [superView addConstraint:topConstraint];
            
//
            NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeRight multiplier:1 constant:0];
            [superView addConstraint:rightConstraint];
//
            NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeBottom multiplier:1 constant:0];
            [superView addConstraint:bottomConstraint];
            
            imageView;
        });
    }
    return self;
}

@end


@interface HBLaunchGuideView ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) UIPageControl *pageView;

@property (nonatomic, strong) UIButton *startButton;

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, copy) void(^startAction)(void);

@end

@implementation HBLaunchGuideView

+ (void)guideViewWithStartButtonTitle:(NSString*)title images:(NSArray<NSString*>*(^)(void))images complete:(void (^)(void))complete{

    if (!images) {
        if (complete) {
            complete();
        }
        return;
    }
    
    HBLaunchGuideView *view = [[self alloc] initWithFrame:[UIScreen mainScreen].bounds];
    NSArray *imagesData = images();
    if (imagesData.count <= 0) {
        if (complete) {
            complete();
        }
        return;
    }
    
    for (int i = 0; i < imagesData.count; i++) {
        NSString *imageName = imagesData[i];
        if (imageName == nil || ![imageName isKindOfClass:[NSString class]] || imageName.length <= 0) continue;
        if (![imageName hasSuffix:@"png"] && ![imageName hasSuffix:@"jpg"] && ![imageName hasSuffix:@"jpeg"] && ![imageName hasSuffix:@"gif"]) {
            imageName = [imageName stringByAppendingString:@".png"];
        }
        NSString *bundlePath = [[NSBundle mainBundle] pathForResource:imageName ofType:nil];
        
        UIImage *image = [UIImage imageWithContentsOfFile:bundlePath];
        if (image) {
            [view.dataSource addObject:image];
        }
    }
    if (view.dataSource.count <= 0) {
        if (complete) {
            complete();
        }
        return;
    }
    if (view.dataSource.count <= 1) {
        view.pageView.hidden = YES;
    }
    [view.startButton setTitle:title forState:UIControlStateNormal];
    //    view.startButton.backgroundColor = [UIColor redColor];
    [view.startButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    
    
    view.pageView.numberOfPages = view.dataSource.count;
    [view.collectionView reloadData];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    if (!window) {
        if (complete) {
            complete();
        }
        return;
    }
    
    [window addSubview:view];
    view.startAction = complete;

}



- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
        UIView *superView = self;
        
        _collectionView = ({
            
            UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
            layout.itemSize = [UIScreen mainScreen].bounds.size;
            layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
            layout.minimumLineSpacing = 0;
            layout.minimumInteritemSpacing = 0;
            
            
            UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:layout];
            [collectionView registerClass:[HBLaunchGuideCell class] forCellWithReuseIdentifier:kHBLaunchGuideCellId];
            collectionView.showsVerticalScrollIndicator = NO;
            collectionView.showsHorizontalScrollIndicator = NO;
            collectionView.backgroundColor = [UIColor whiteColor];
            collectionView.bounces = NO;
            collectionView.pagingEnabled = YES;
            [superView addSubview:collectionView];
            collectionView.delegate = self;
            collectionView.dataSource = self;
            collectionView;
        });
        
        _pageView = ({
            UIPageControl *pageView = [[UIPageControl alloc] init];
            //            pageView.hidden = YES;
            pageView.currentPageIndicatorTintColor = [UIColor grayColor];
            pageView.pageIndicatorTintColor = [UIColor whiteColor];
            [superView addSubview:pageView];
            pageView.currentPage = 0;
            pageView.translatesAutoresizingMaskIntoConstraints = NO;
            NSLayoutConstraint *bottomConstraints = [NSLayoutConstraint constraintWithItem:pageView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeBottom multiplier:1 constant:-44];
            [superView addConstraint:bottomConstraints];

            NSLayoutConstraint *leftConstraints = [NSLayoutConstraint constraintWithItem:pageView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeLeft multiplier:1 constant:0];
            [superView addConstraint:leftConstraints];

            NSLayoutConstraint *rightConstraints = [NSLayoutConstraint constraintWithItem:pageView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeRight multiplier:1 constant:0];
            [superView addConstraint:rightConstraints];

            NSLayoutConstraint *heightConstraints = [NSLayoutConstraint constraintWithItem:pageView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1 constant:5];
            [superView addConstraint:heightConstraints];

            pageView;
        });

        _startButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.backgroundColor = [UIColor whiteColor];
            CGFloat height = 44;
            button.layer.cornerRadius = height * 0.5;
            button.layer.borderColor = [UIColor redColor].CGColor;
            button.layer.borderWidth = 0.5;
            button.alpha = 0;
            button.layer.masksToBounds = YES;
            button.translatesAutoresizingMaskIntoConstraints = NO;
            button.titleLabel.font = [UIFont systemFontOfSize:18];
            [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
            [superView addSubview:button];

            NSLayoutConstraint *bottomConstraints = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeBottom multiplier:1 constant:-100];
            [superView addConstraint:bottomConstraints];

            NSLayoutConstraint *centerXConstraints = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
            [superView addConstraint:centerXConstraints];

            NSLayoutConstraint *widthConstraints = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeWidth multiplier:(400.0f/720.0f) constant:0];
            [superView addConstraint:widthConstraints];

            NSLayoutConstraint *heightConstraints = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1 constant:height];
            [superView addConstraint:heightConstraints];

            button;
        });
    }
    return self;
}

#pragma mark - <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HBLaunchGuideCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kHBLaunchGuideCellId forIndexPath:indexPath];
    cell.imageView.image = self.dataSource[indexPath.row] ;
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView.contentOffset.x == (scrollView.contentSize.width - scrollView.frame.size.width)) {
        [UIView animateWithDuration:0.25 animations:^{
            self.startButton.alpha = 1;
        }];
        
    }else{
        self.startButton.alpha = 0;
        
    }
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger index = scrollView.contentOffset.x / CGRectGetWidth(scrollView.frame);
    self.pageView.currentPage = index;
}

#pragma mark - Action

-  (void)buttonAction{
    //    NSLog(@"点击");
    
    
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        if (self.startAction) {
            self.startAction();
        }
        [self removeFromSuperview];
    }];
    
}


- (void)dealloc{
    NSLog(@"%s",__func__);
}
#pragma mark - 懒加载

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

@end
